package com.baosight.sczx.zm.cm.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.zm.Utils;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cm.MaterialBase;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCM;
import com.baosight.sczx.zm.cm.domain.ZMCMImportMaterial;
import com.baosight.sczx.zm.cm.domain.ZMCMImportmaterialDetail;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialBase;
import com.baosight.sczx.zm.cm.domain.ZMCMMaterialType;

public class ServiceZMCMB3 extends ServiceEPBase {
	
	private static final String NOTE_BLOCK = "noteBlock";

	public EiInfo initLoad(EiInfo inInfo)
	{
		return this.query(inInfo);
	}
	
	/**
	 * 
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCMB3</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:32:28 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo query(EiInfo inInfo)
	{
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		String fdImportmaterialIds = inInfo.getBlock(EiConstant.queryBlock).getRow(0).get("fdImportmaterialId").toString();
		String fdMaterialName = inInfo.getBlock(EiConstant.queryBlock).getCellStr(0, "fdMaterialName");
		String fdMaterialCode = inInfo.getBlock(EiConstant.queryBlock).getCellStr(0, "fdMaterialCode");
		String fdSpecModel = inInfo.getBlock(EiConstant.queryBlock).getCellStr(0, "fdSpecModel");
		String fdProvideDepartment = inInfo.getBlock(EiConstant.queryBlock).getCellStr(0, "fdProvideDepartment");
		String[] ids = fdImportmaterialIds.split(";");
		String typeCode = "";
		EiBlock block = inInfo.getBlock(EiConstant.resultBlock);
		block.addBlockMeta((new ZMCMImportmaterialDetail()).eiMetadata);
		
		for(int i=0; i<ids.length; i++)
		{
			Map inMap = new HashMap();
			String sqlmap = "ZMCMTypeManageMentSet.queryManageAllType";
			String isUseTypeManagement = SystemSettingCM.getInstance().getIsuseTypemanagement();
			if(isUseTypeManagement.equals("1"))
			{
				inMap.put("fdImportPeopleId", UserSession.getUserId());
				List _list = dao.query(sqlmap, inMap);
				List queryList = Utils.generateValidateData(_list);
				typeCode = "(FD_MATERIAL_CODE like ''";
				for(int j=0; j<queryList.size(); j++)
				{
					typeCode += " OR FD_MATERIAL_CODE like '" + queryList.get(j).toString() + "%'";
				}
				typeCode += ")";
			}
			else
			{
				sqlmap = "ZMCMMaterialType.type";
				List queryList = dao.query(sqlmap, inMap);
				
				typeCode = "(FD_MATERIAL_CODE like ''";
				for(int j=0; j<queryList.size(); j++)
				{
					Map _map = (Map)queryList.get(j);
					typeCode += " OR FD_MATERIAL_CODE like '" + _map.get("fdTypeCode").toString() + "%'";
				}
				typeCode += ")";
			}

			inMap = new HashMap();
			inMap.put("fdImportmaterialId", ids[i]);
			inMap.put("fdStatus", "部分");
			inMap.put("fdMaterialCodeStr", typeCode);
			inMap.put("fdMaterialName", fdMaterialName);
			inMap.put("fdMaterialCode", fdMaterialCode);
			inMap.put("fdSpecModel", fdSpecModel);
			inMap.put("fdProvideDepartment", fdProvideDepartment);
	    	
			List tmp_list = dao.query("ZMCMImportmaterialDetail.query", inMap);

			if((fdMaterialName != null || fdMaterialCode != null
					|| fdSpecModel != null) && tmp_list.size() == 0)
			{
				EiInfo outInfo = new EiInfo();
				outInfo.addBlock(new EiBlock(EiConstant.resultBlock));
				return inInfo;
			}
			
			if(tmp_list.size() <= 0)
			{
				inInfo.setStatus(-1);
				inInfo.setMsg("没有可估收的物资或没有该入库单中物资的分管权限！");
				return inInfo;
			}
			
			for(int j=0; j<tmp_list.size(); j++)
			{
				block.addRow((ZMCMImportmaterialDetail)tmp_list.get(j));
			}
		}
		
		inInfo.set("fdNoteCode", queryNoteCode());
		return inInfo;
	}
	
	/**
	 * 
	 * <p>Function: minusEvaluation</p>
	 * <p>Description: 估收红冲入库</p>
	 * <p>return value:EiInfo</p>
	 * <p>History:
	 *    2011-9-13上午10:36:45 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo minusEvaluation(EiInfo inInfo)
	{
		EiInfo tmpInfo = validateAccountMonth(inInfo);
		if(tmpInfo.getStatus() == -1)
		{
			return tmpInfo;
		}
		
		if(!validateSum(inInfo))
		{
			return inInfo;
		}
		String fdImportmaterialIds = inInfo.getBlock(NOTE_BLOCK).getRow(0).get("fdOldKeyId").toString();
		String[] ids = fdImportmaterialIds.split(";");
		
		//校验选中入库单是否已经红冲估收
		if(!validateNoteCodeUnique(inInfo))
		{
			return inInfo;
		}
		
//		if(!validateNotExceed(inInfo))
//		{
//			inInfo.setStatus(-1);
//			inInfo.setMsg("实际库存金额与发票金额的总和，小于选中估收单的金额，会造成实际库存金额与单价为负，请确认选中估收单明细的单价是否估算过高！");
//			
//			return inInfo;
//		}
		
		//新增超出数量的正式入库单
		newExceedImport(inInfo);
		
		//新增红冲入库单
		minusImport(inInfo, true);
		//新增正式入库单
		minusImport(inInfo, false);
		
		for(int i=0; i<ids.length; i++)
		{
			Map inMap = new HashMap();
			inMap.put("fdImportmaterialId", ids[i]);
			List tmp_list = dao.query("ZMCMImportmaterialDetail.queryAllStatus", inMap);
			boolean flag = false;

			for(int j=0; j<tmp_list.size(); j++)
			{
				Map tmp_map = (Map)tmp_list.get(j);
				if(tmp_map.get("fdStatus") == null || !tmp_map.get("fdStatus").equals("全部"))
				{
					flag = true;
				}
			}
			
			if(!flag)
			{
				inMap.put("fdStatus", "全部");
			}
			else
			{
				inMap.put("fdStatus", "部分");
			}
			dao.update("ZMCMImportMaterial.updateStatus", inMap);
		}
		
		return super.query(inInfo, "ZMCMImportMaterial.query", new ZMCMImportMaterial());
	}
	
	/**
	 * 
	 * <p>Function: validateNoteCodeUnique</p>
	 * <p>Description: 验证单据编号是否唯一</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-15下午02:35:06 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean validateNoteCodeUnique(EiInfo inInfo)
	{
		String fdNodeCode = (String)inInfo.getBlock(NOTE_BLOCK).getRow(0).get("fdNoteCode");
		Map inMap = new HashMap();
		inMap.put("fdNoteCode", fdNodeCode);
		
		List _list = dao.query("ZMCMImportMaterial.validate", inMap);
		if(_list != null && _list.size() > 0) {
			StringBuffer msg = new StringBuffer("提交失败，单据编号重复!");
			inInfo.setStatus(-1);
			inInfo.setMsg(msg.toString());
			return false;
		}
		
		return true;
	}
	
	/**
	 * 
	 * <p>Function: validateNoteCodeUnique</p>
	 * <p>Description: 验证冲估的单据的金额，小于实际库存金额和发票金额的总和</p>
	 * <p>return value:boolean</p>
	 * <p>History:
	 *    2011-9-15下午02:35:06 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private boolean validateNotExceed(EiInfo inInfo)
	{
		List _list = inInfo.getBlock(EiConstant.resultBlock).getRows();

		for(int i=0; i<_list.size(); i++)
		{
			Map infoMap = (Map)_list.get(i);
			
			Map _map = new HashMap();
			_map.put("fdMaterialId", infoMap.get("fdMaterialId"));
			
			List base_list = dao.query("ZMCMMaterialBase.query", _map);
			
			if(base_list.size() > 0)
			{
				ZMCMMaterialBase mb = (ZMCMMaterialBase)base_list.get(0);
				String str_ActualNumber = infoMap.get("fdActualNumber").toString();
				String str_InvoiceSum = infoMap.get("fdInvoiceSum").toString();
				String str_resourceNotePrice = infoMap.get("fdPrice").toString();
				
				double fdActualNumber = Double.parseDouble(str_ActualNumber.equals("")? "0": str_ActualNumber);
				double fdInvoiceSum = Double.parseDouble(str_InvoiceSum.equals("")? "0": str_InvoiceSum);
				double fdResourceNotePrice = Double.parseDouble(str_resourceNotePrice.equals("")? "0": str_resourceNotePrice);
				double fdActualSum = mb.getFdActualSum();
				
				if((fdActualSum-fdActualNumber*fdResourceNotePrice+fdInvoiceSum) < Double.parseDouble("0.0"))
				{
					return false;
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 
	 * <p>Function: minusImport</p>
	 * <p>Description: 新增红冲入库单</p>
	 * <p>return value:void</p>
	 * <p>History:
	 *    2011-9-15下午04:17:06 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void minusImport(EiInfo inInfo, boolean isMinus)
	{
		//boolean result = false;
		
		String fdKeyId = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL");
		String newNoteCode = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdNoteCode");
		String resourceNoteCode = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdResourceNoteCode");
		String noteDate = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdNoteDate");
		String fdDepotCode = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdDepotCode");
		String fdDepotName = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdDepotName");
		
		Map inMap = new HashMap();
		inMap.put("fdKeyId", fdKeyId);
		inMap.put("fdResourceNoteCode", resourceNoteCode);
		inMap.put("fdDepotCode", fdDepotCode);
		inMap.put("fdDepotName", fdDepotName);
		
		//如果是新增红冲单据
		if(isMinus)
		{
			if(resourceNoteCode.length() > 27)
			{
				newNoteCode = "HC_"+resourceNoteCode.substring(0, 27);
			}
			else
			{
				newNoteCode = "HC_"+resourceNoteCode;
			}
			
			inMap.put("fdImportType", "红冲");
		}
		//如果是新增一般入库单据
		else
		{
			inMap.put("fdImportType", "一般入库");
		}

		inMap.put("fdNoteCode", newNoteCode);
		inMap.put("fdStatus", "");
		inMap.put("fdNoteDate", noteDate);
		inMap.put("fdEditor", UserSession.getUserId());
		inMap.put("fdRemark", "");
		inMap.put("fdYear", MaterialBase.getAccountDate(StaticTools.getDate())[0]);
		inMap.put("fdMonth", MaterialBase.getAccountDate(StaticTools.getDate())[1]);
		dao.insert("ZMCMImportMaterial.insert", inMap);
		
		minusImportDetail(inInfo, fdKeyId, isMinus);
	}
	
	/**
	 * 
	 * <p>Function: minusImportDetail</p>
	 * <p>Description: 新增红冲入库单明细</p>
	 * <p>return value:void</p>
	 * <p>History:
	 *    2011-9-15下午04:16:55 bobswang
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void minusImportDetail(EiInfo inInfo, String fdPrimaryKeyId, boolean isMinus)
	{
		List _list = inInfo.getBlock(EiConstant.resultBlock).getRows();

		for(int i=0; i<_list.size(); i++)
		{
			Map infoMap = (Map)_list.get(i);
			
			String fdKeyId = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL_DETAIL");
			String fdOldKeyId = infoMap.get("fdKeyId").toString();
			
			Map inMap = new HashMap();
			inMap.put("fdKeyId", fdKeyId);
			inMap.put("fdImportmaterialId", fdPrimaryKeyId);
			inMap.put("fdProvideDepartment", infoMap.get("fdProvideDepartment"));
			inMap.put("fdMaterialSource", infoMap.get("fdMaterialSource"));
			inMap.put("fdMaterialId", infoMap.get("fdMaterialId"));
			inMap.put("fdMaterialCode", infoMap.get("fdMaterialCode"));
			inMap.put("fdMaterialName", infoMap.get("fdMaterialName"));
			inMap.put("fdSpecModel", infoMap.get("fdSpecModel"));
			inMap.put("fdNumber", infoMap.get("fdNumber"));
			inMap.put("fdQuality", infoMap.get("fdQuality"));
			inMap.put("fdStatus", infoMap.get("fdStatus"));
			inMap.put("fdReduceNumber", "0");
			inMap.put("fdMetric", infoMap.get("fdMetric"));
			inMap.put("fdPrice", infoMap.get("fdPrice"));
			inMap.put("fdConfirmPeople", infoMap.get("fdConfirmPeople"));
			inMap.put("fdRemark", infoMap.get("fdRemark"));
			
			//如果是新增红冲单据
			if(isMinus)
			{
				Double fdActualNumber = (Double.parseDouble(infoMap.get("fdActualNumber").toString())-
						 					Double.parseDouble(infoMap.get("fdExceedNumber").toString()));
				//原单单价=原单金额/原单数量
				Double fdPrice = Double.parseDouble(infoMap.get("fdSum").toString())/Double.parseDouble(infoMap.get("fdResourceNumber").toString());
				
				inMap.put("fdSum", (0-(fdActualNumber*fdPrice))+"");
				inMap.put("fdPlanNumber", (0-fdActualNumber)+"");
				inMap.put("fdActualNumber", (0-fdActualNumber)+"");
				inMap.put("fdInvoice", "0");
				inMap.put("fdInvoiceSum", "0");
			}
			//如果新增一般入库
			else
			{
				Double fdActualNumber = (Double.parseDouble(infoMap.get("fdActualNumber").toString())-
 											Double.parseDouble(infoMap.get("fdExceedNumber").toString()));
				Double fdPrice = Double.parseDouble(infoMap.get("fdPrice").toString());
				
				inMap.put("fdSum", (fdActualNumber*fdPrice)+"");
				inMap.put("fdPlanNumber", fdActualNumber);
				inMap.put("fdActualNumber", fdActualNumber);
				inMap.put("fdInvoice", infoMap.get("fdInvoice"));
				inMap.put("fdInvoiceSum", infoMap.get("fdInvoiceSum"));
			}
			
			//插入新的入库明细
			dao.insert("ZMCMImportmaterialDetail.insert", inMap);
			
			if(isMinus)
			{
				inMap = new HashMap();
				inMap.put("fdReduceNumber", infoMap.get("fdReduceNumber")+"");
				Double.parseDouble(infoMap.get("fdReduceNumber").toString());
				Double.parseDouble(infoMap.get("fdResourceNumber").toString());

				if(Double.parseDouble(infoMap.get("fdReduceNumber").toString()) 
						== Double.parseDouble(infoMap.get("fdResourceNumber").toString()))
				{
					inMap.put("fdStatus", "全部");
				}
				else
				{
					inMap.put("fdStatus", "部分");
				}
				inMap.put("fdKeyId", fdOldKeyId);
				
				minusBaseMeterial(infoMap);
				
				//更新原单据的已冲数量
				dao.update("ZMCMImportmaterialDetail.updateReduceNum", inMap);
			}
		}
	}
	
	/**
	 * 
	 * <p>Function: minusBaseMeterial</p>
	 * <p>Description: </p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-12-2上午03:34:03 严洪浩
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void minusBaseMeterial(Map infoMap)
	{
		double fdActualNumber = (Double.parseDouble(infoMap.get("fdActualNumber").toString())-
					Double.parseDouble(infoMap.get("fdExceedNumber").toString()));
		Map _map = new HashMap();
		_map.put("fdMaterialId", infoMap.get("fdMaterialId"));
		
		List _list = dao.query("ZMCMMaterialBase.query", _map);
		
		if(_list.size() > 0)
		{
			ZMCMMaterialBase mb = (ZMCMMaterialBase)_list.get(0);
			String str_ActualNumber = infoMap.get("fdActualNumber").toString();
			String str_InvoiceSum = infoMap.get("fdInvoiceSum").toString();
			String str_oldPrice = infoMap.get("fdPrice").toString();
			
			double fdInvoiceSum = Double.parseDouble(str_InvoiceSum.equals("")? "0": str_InvoiceSum);
			double oldPrice = Double.parseDouble(str_oldPrice.equals("")? "0": str_oldPrice);
			double fdPrice = mb.getFdPrice();
			double fdActualSum = mb.getFdActualSum();
			
			//修改库存中物资数量、金额等
			Map inMap = new HashMap();
			inMap.put("fdMaterialId", mb.getFdMaterialId());
			
			inMap.put("fdNum", mb.getFdNum()+"");
			
			if(mb.getFdNoinvoiceUseNum()-fdActualNumber>=0)
			{
				inMap.put("fdNoInvoiceUseNum", mb.getFdNoinvoiceUseNum()-fdActualNumber);
				inMap.put("fdHasinvoiceNum", mb.getFdHasinvoiceNum()+"");
				inMap.put("fdNoinvoiceNum", mb.getFdNoinvoiceNum()+"");
			}
			else
			{
				inMap.put("fdNoInvoiceUseNum", "0");
				//当冲估数量大于无发票数量时(在已用了估收的量会出现)，有发票数量只加无发票数量即可
				if(mb.getFdNoinvoiceNum()-(fdActualNumber-mb.getFdNoinvoiceUseNum()) > 0)
				{
					inMap.put("fdHasinvoiceNum", (mb.getFdHasinvoiceNum()==null?0.0:mb.getFdHasinvoiceNum())+(fdActualNumber-mb.getFdNoinvoiceUseNum())+"");
					inMap.put("fdNoinvoiceNum", mb.getFdNoinvoiceNum()-(fdActualNumber-mb.getFdNoinvoiceUseNum())+"");
				}
				else
				{
					inMap.put("fdHasinvoiceNum", (mb.getFdHasinvoiceNum()==null?0.0:mb.getFdHasinvoiceNum())+mb.getFdNoinvoiceNum()-(fdActualNumber-mb.getFdNoinvoiceUseNum())+"");
					inMap.put("fdNoinvoiceNum", "0");
				}
			}			
			
			inMap.put("fdSum", fdPrice*mb.getFdNum()+"");
			inMap.put("fdPrice", fdPrice+"");
			inMap.put("fdLastImportDate", StaticTools.getDate());
			
			if(mb.getFdNum() != Double.parseDouble("0"))
			{
				inMap.put("fdActualPrice", BigDecimal.valueOf((fdActualSum-fdActualNumber*oldPrice+fdInvoiceSum)/mb.getFdNum()));
			}
			else
			{
				inMap.put("fdActualPrice", mb.getFdActualPrice());
			}
			inMap.put("fdActualSum", BigDecimal.valueOf(fdActualSum-fdActualNumber*oldPrice+fdInvoiceSum));
							
			dao.update("ZMCMMaterialBase.updateAfterStorage", inMap);
			
			dao.update("ZMCMMaterialBase.updateNoInvoiceUseNum", inMap);
		}
	}
	
	/**
	 * 
	 * <p>Function: newExceedImport</p>
	 * <p>Description: 超出部分办理正式入库</p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-30下午02:01:46 wangkun
	 * </p>
	 *
	 */
	private void newExceedImport(EiInfo inInfo)
	{
		List _list = inInfo.getBlock(EiConstant.resultBlock).getRows();
		boolean hasExceedFlag = false;
		for(int i=0; i<_list.size(); i++)
		{
			Map infoMap = (Map)_list.get(i);
			
			if((Double.parseDouble("0")) != Double.parseDouble(infoMap.get("fdExceedNumber").toString()))
			{
				hasExceedFlag = true;
			}
		}
		
		if(hasExceedFlag)
		{
			String fdKeyId = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL");
			String noteCode = queryNoteCode();
			String noteDate = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdNoteDate");
			String fdDepotCode = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdDepotCode");
			String fdDepotName = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdDepotName");
			
			Map inMap = new HashMap();
			inMap.put("fdKeyId", fdKeyId);
			inMap.put("fdResourceNoteCode", "");
			inMap.put("fdDepotCode", fdDepotCode);
			inMap.put("fdDepotName", fdDepotName);
			inMap.put("fdImportType", "一般入库");
	
			inMap.put("fdNoteCode", noteCode);
			inMap.put("fdStatus", "");
			inMap.put("fdNoteDate", noteDate);
			inMap.put("fdEditor", UserSession.getUserId());
			inMap.put("fdRemark", "");
			inMap.put("fdYear", MaterialBase.getAccountDate(noteDate)[0]);
			inMap.put("fdMonth", MaterialBase.getAccountDate(noteDate)[1]);
			dao.insert("ZMCMImportMaterial.insert", inMap);
	
			for(int i=0; i<_list.size(); i++)
			{
				Map infoMap = (Map)_list.get(i);
				
				if((Double.parseDouble("0")) != Double.parseDouble(infoMap.get("fdExceedNumber").toString()))
				{
					String fdDetailKeyId = TablePk.getInstance().getNextValue("T_CM_IMPORTMATERIAL_DETAIL");
					
					inMap = new HashMap();
					inMap.put("fdKeyId", fdDetailKeyId);
					inMap.put("fdImportmaterialId", fdKeyId);
					inMap.put("fdProvideDepartment", infoMap.get("fdProvideDepartment"));
					inMap.put("fdMaterialSource", infoMap.get("fdMaterialSource"));
					inMap.put("fdMaterialId", infoMap.get("fdMaterialId"));
					inMap.put("fdMaterialCode", infoMap.get("fdMaterialCode"));
					inMap.put("fdMaterialName", infoMap.get("fdMaterialName"));
					inMap.put("fdSpecModel", infoMap.get("fdSpecModel"));
					inMap.put("fdNumber", infoMap.get("fdNumber"));
					inMap.put("fdQuality", infoMap.get("fdQuality"));
					inMap.put("fdStatus", infoMap.get("fdStatus"));
					inMap.put("fdReduceNumber", "0");
					inMap.put("fdMetric", infoMap.get("fdMetric"));
					inMap.put("fdPrice", infoMap.get("fdPrice"));
					inMap.put("fdConfirmPeople", infoMap.get("fdConfirmPeople"));
					inMap.put("fdRemark", infoMap.get("fdRemark"));
					
		
					Double fdActualNumber = Double.parseDouble(infoMap.get("fdExceedNumber").toString());
					Double fdPrice = Double.parseDouble(infoMap.get("fdPrice").toString());
					
					inMap.put("fdSum", (fdActualNumber*fdPrice)+"");
					inMap.put("fdPlanNumber", infoMap.get("fdExceedNumber"));
					inMap.put("fdActualNumber", infoMap.get("fdExceedNumber"));
					inMap.put("fdInvoice", infoMap.get("fdInvoice"));
					inMap.put("fdInvoiceSum", infoMap.get("fdInvoiceSum"));
					
					//插入新的入库明细
					dao.insert("ZMCMImportmaterialDetail.insert", inMap);
					
					Map baseMap = new HashMap();
					baseMap.put("fdMaterialId", infoMap.get("fdMaterialId"));
					baseMap.put("fdActualNumber", infoMap.get("fdExceedNumber"));
					baseMap.put("fdInvoiceSum", (fdActualNumber*fdPrice)+"");
					baseMap.put("fdPrice", infoMap.get("fdPrice"));
					
					insertNewMeterial(baseMap);
				}
			}
		}
	}
	
	/**
	 * 
	 * <p>Function: insertNewMeterial</p>
	 * <p>Description: 增加超出物资的入库</p>
	 * <p>return value:void</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-4-10下午03:59:54 wangkun
	 * </p>
	 *
	 */
	private void insertNewMeterial(Map infoMap)
	{
		Map _map = new HashMap();
		_map.put("fdMaterialId", infoMap.get("fdMaterialId"));
		
		List _list = dao.query("ZMCMMaterialBase.query", _map);
		
		if(_list.size() > 0)
		{
			ZMCMMaterialBase mb = (ZMCMMaterialBase)_list.get(0);
			String str_ActualNumber = infoMap.get("fdActualNumber").toString();
			String str_InvoiceSum = infoMap.get("fdInvoiceSum").toString();
			String str_oldPrice = infoMap.get("fdPrice").toString();
			
			double fdActualNumber = Double.parseDouble(str_ActualNumber.equals("")? "0": str_ActualNumber);
			double fdInvoiceSum = Double.parseDouble(str_InvoiceSum.equals("")? "0": str_InvoiceSum);
			double oldPrice = Double.parseDouble(str_oldPrice.equals("")? "0": str_oldPrice);
			double fdPrice = mb.getFdPrice();
			double fdActualSum = mb.getFdActualSum();
			
			//修改库存中物资数量、金额等
			Map inMap = new HashMap();
			inMap.put("fdMaterialId", mb.getFdMaterialId());
			
			inMap.put("fdNum", (mb.getFdNum()+fdActualNumber)+"");
			inMap.put("fdNoinvoiceNum", mb.getFdNoinvoiceNum()+"");
			inMap.put("fdHasinvoiceNum", ((mb.getFdHasinvoiceNum()==null?0.0:mb.getFdHasinvoiceNum())+fdActualNumber)+"");
			inMap.put("fdSum", fdPrice*(mb.getFdNum()+fdActualNumber)+"");
			inMap.put("fdPrice", fdPrice+"");
			inMap.put("fdLastImportDate", StaticTools.getDate());
			
			if(mb.getFdNum() != Double.parseDouble("0"))
			{
				inMap.put("fdActualPrice", BigDecimal.valueOf((fdActualSum+fdInvoiceSum)/(mb.getFdNum()+fdActualNumber)));
			}
			else
			{
				inMap.put("fdActualPrice", mb.getFdActualPrice());
			}
			inMap.put("fdActualSum", BigDecimal.valueOf(fdActualSum+fdInvoiceSum));
							
			dao.update("ZMCMMaterialBase.updateAfterStorage", inMap);
		}
	}
	
	/**
	 * 
	 * <p>Function: validateAccountMonth</p>
	 * <p>Description: 校验是否在正确的记账周期内</p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-30下午04:11:26 wangkun
	 * </p>
	 *
	 */
	public EiInfo validateAccountMonth(EiInfo inInfo)
	{
		String date1 = inInfo.getBlock(NOTE_BLOCK).getCellStr(0, "fdNoteDate");		
		if(date1 == null || "".equals(date1))//如果没有得到日期，默认为当前日期
		{
			date1 = StaticTools.getDate();
		}
		int result_int = MaterialBase.isInAccountDate(date1);
		if(result_int == -2)
		{
			inInfo.setStatus(-1);
			//StringBuffer msg = new StringBuffer("当前日期已经超出" + MaterialBase.getAccountDate(StaticTools.getDate())[2] + "月的记账范围，请在结转库存后，再办理入库！");
			StringBuffer msg = new StringBuffer("上个月没有做库存结转，请在结转库存后，再办理入库！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		if(result_int == 0)
		{
			inInfo.setStatus(-1);
			StringBuffer msg = new StringBuffer("该开单日期所在" + MaterialBase.getAccountDate(date1)[2] + "月的库存已经结转，无法办理入库！");
			inInfo.setMsg(msg.toString());
			return inInfo;
		}
		return inInfo;
	}
	
	private boolean validateSum(EiInfo inInfo)
	{
		boolean result = false;
		List wholeSumlist = new ArrayList();
		List _list = dao.query("ZMCMMaterialType.querySum", new HashMap());
		
		for(int i=0; i<_list.size(); i++)
		{
			ZMCMMaterialType type = (ZMCMMaterialType)_list.get(i);
			Map inMap = new HashMap();
			inMap.put("fdTypeCode", type.getFdTypeCode());
			inMap.put("fdSum", type.getFdSum());
			Map _map = new HashMap();
			_map.put("fdMaterialCode", type.getFdTypeCode());
			List sum_list = dao.query("ZMCMMaterialBase.queryInvoiceSum", _map);
			if(sum_list.size()>0)
			{
				inMap.put("fdActualSum", ((Map)sum_list.get(0)).get("fd_sum"));
			}
			else
			{
				inMap.put("fdActualSum", "0.0");
			}
			wholeSumlist.add(inMap);
		}
		
		for(int i=0; i<inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++)
		{
			Map infoMap = (Map)inInfo.getBlock(EiConstant.resultBlock).getRows().get(i);
			
			String fdMaterialCode = (String)infoMap.get("fdMaterialCode");
			String fdInvoiceSum = (String)infoMap.get("fdInvoiceSum");
			for(int j=0; j<wholeSumlist.size(); j++)
			{
				if(fdMaterialCode.startsWith(((Map)wholeSumlist.get(j)).get("fdTypeCode").toString()))
				{
					Map _map = (Map)wholeSumlist.get(j);
					double sum = Double.parseDouble(_map.get("fdActualSum").toString())+Double.parseDouble(fdInvoiceSum);
					if(sum-Double.parseDouble(_map.get("fdSum").toString())>0)
					{
						inInfo.setStatus(-1);
						inInfo.setMsg("选中的[" + ((Map)wholeSumlist.get(j)).get("fdTypeCode").toString()+
										"]类的物资，超出额度上限，不允许红冲估收！");
						return false;
					}
					else
					{
						_map.put("fdActualSum", sum+"");
					}
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 
	 * <p>Function: queryNoteCode</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-14上午10:48:09 wangkun
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryNoteCode()
	{
		List<Map> _list = new ArrayList<Map>();
		HashMap	params = new HashMap<String, String>();
		String startStr = "RK" + StaticTools.getDateDefault() + StaticTools.getTime().replaceAll(":", "");
		String defaultStr = startStr + "001";//定义格式
		_list = dao.query("ZMCMImportMaterial.querySerialNum", params);
		if(_list!=null && _list.size() > 0) {
			String str = _list.get(0).get("fdNoteCode").toString();
			defaultStr = convertStr(startStr, str);
		}
		
		return defaultStr;
	}
	
	/**
	 * 
	 * <p>Function: convertStr</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-3-14上午10:48:03 wangkun
	 * </p>
	 *
	 */
	private String convertStr(String startStr, String str)
	{
		String str1 = str.substring(16,19);//第二部分的流水号
		int nub = Integer.parseInt(str1); 
		str1 = Integer.toString(nub+1);
		if(str1.length() == 1){
			return startStr+"00"+str1;
		}else if (str1.length() == 2)
		{
			return startStr+"0"+str1;
		}else
		{
			return startStr+str1;
		}
	}
}
